import 'package:flutter/material.dart';
import 'package:flutter_baselib/lib.dart';
import 'package:flutter_baselib/src/ui/load_state/load_empty_view.dart';
import 'package:flutter_baselib/src/ui/load_state/load_error_view.dart';
import 'package:flutter_baselib/src/ui/load_state/load_state_parent_view.dart';
import 'package:flutter_baselib/src/ui/load_state/loading_view.dart';

///@date:  2021/3/1 13:38
///@author:  lixu
///@description:View 基类,配合[BaseViewModel]使用
///封装：通用加载页,集成了加载失败和加载为空的逻辑
// ignore: must_be_immutable
class BaseView<T extends BaseViewModel> extends StatefulWidget {
  ///加载成功后显示的页面
  final Widget child;

  ///加载中页面
  Widget loadingChild;

  ///数据为空的页面
  Widget emptyChild;

  ///请求失败显示的页面
  Widget errorChild;

  BaseView({@required this.child, this.loadingChild, this.emptyChild, this.errorChild}) : assert(child != null);

  @override
  _BaseViewState<T> createState() => _BaseViewState<T>();
}

class _BaseViewState<T extends BaseViewModel> extends State<BaseView> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Consumer<T>(
      child: widget.child,
      builder: (BuildContext context, T viewModel, Widget child) {
        if (viewModel.isSuccess()) {
          return child;
        } else {
          return FutureBuilder(
            future: viewModel.onLoading(context),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (viewModel.isFail()) {
                  ///加载失败
                  return _getErrorWidget(viewModel);
                } else if (viewModel.isEmpty()) {
                  ///数据为空
                  return _getEmptyWidget(viewModel);
                } else {
                  ///加载成功
                  return child;
                }
              } else {
                ///加载中
                return _getLoadingWidget();
              }
            },
          );
        }
      },
    );
  }

  Widget _getErrorWidget(T viewModel) {
    return widget.errorChild != null
        ? widget.errorChild
        : LoadStateParentView(
            BaseLibPlugin.resConfig.configLoadErrorView() ?? LoadErrorView(),
            _onRefresh(viewModel),
          );
  }

  Widget _getEmptyWidget(T viewModel) {
    return widget.emptyChild != null
        ? widget.emptyChild
        : LoadStateParentView(
            BaseLibPlugin.resConfig.configLoadEmptyView() ?? LoadEmptyView(),
            _onRefresh(viewModel),
          );
  }

  Widget _getLoadingWidget() {
    return LoadStateParentView(
      widget.loadingChild != null ? widget.loadingChild : BaseLibPlugin.resConfig.configLoadingView() ?? LoadingView(),
      null,
    );
  }

  ///刷新页面
  VoidCallback _onRefresh(T viewModel) {
    return () {
      viewModel?.retryRefresh();
    };
  }

  @override
  bool get wantKeepAlive => true;
}
